package com.ruoyi.pay.service;

import com.github.wxpay.sdk.WXPayUtil;

import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.pay.response.Result;
import okhttp3.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WXPayService {



    @Autowired
    RabbitTemplate rabbitTemplate;

    //@Autowired
    //PaymentInfoMapper paymentInfoMapper;
    /*
    weixin:
      appid: wxab8acb865bb1637e
      partner: 11473623
      partnerkey: 2ab9071b06b9f739b950ddb41db2690d
      notifyurl:  http://wk9k36.natappfree.cc/api/wxpay/notify_url
     */
    @Value("${weixin.appid}")
    String appid;
    @Value("${weixin.partner}")
    String partner;
    @Value("${weixin.partnerkey}")
    String partnerkey;
    @Value("${weixin.notifyurl}")
    String notifyurl;
    /**
     * 完成对微信 NATIVE  统一下单接口的封装
     * @param orderId
     * @param totalFee
     */
    public String unifiedOrder(Long orderId, Integer totalFee, String body) throws Exception {
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();//POSTman

        Map map = new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("nonce_str", WXPayUtil.generateNonceStr());//nonce  number once
        map.put("body", body);
        map.put("out_trade_no", String.valueOf(orderId));
        map.put("total_fee", String.valueOf(totalFee));
        map.put("spbill_create_ip", "127.0.0.1");
        map.put("notify_url", notifyurl);//
        map.put("trade_type", "NATIVE");

        String sign = WXPayUtil.generateSignature(map, partnerkey);
        map.put("sign", sign);
        String requestBodyXml = WXPayUtil.mapToXml(map);

        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/xml"),
                requestBodyXml);
        Request request = new Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/unifiedorder") //URL
                .addHeader("Content-Type", "application/xml")
                .post(requestBody)//POST   requestBody
                .build();
        //点击 发送
        Response response = okHttpClient.newCall(request).execute();
        System.out.println("successful = " + response.isSuccessful());
        System.out.println("code = " + response.code());//200
        System.out.println("message = " + response.message());//OK
        System.out.println("headers = " + response.headers());

        String responseBody_xml = response.body().string();

        System.out.println(responseBody_xml);

        Map<String, String> responseBodyMap = WXPayUtil.xmlToMap(responseBody_xml);

        String return_code = responseBodyMap.get("return_code");
        String return_msg = responseBodyMap.get("return_msg");
        if(return_code.equalsIgnoreCase("SUCCESS")){
            String result_code = responseBodyMap.get("result_code");
            String err_code_des = responseBodyMap.get("err_code_des");
            if(result_code.equalsIgnoreCase("SUCCESS")){
                String code_url = responseBodyMap.get("code_url");
                return  code_url;
            }else{

                return  err_code_des;
            }
        }

        return null;
    }

    public AjaxResult orderQuery(Long orderId) throws Exception {
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();//POSTman

        Map map = new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("out_trade_no",String.valueOf(orderId));
        map.put("nonce_str",WXPayUtil.generateNonceStr());

        String sign = WXPayUtil.generateSignature(map, partnerkey);
        map.put("sign",sign);

        String requestBodyXml = WXPayUtil.mapToXml(map);
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/xml"),
                requestBodyXml);

        Request request = new  Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/orderquery")
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();
        System.out.println("successful = " + response.isSuccessful());
        System.out.println("code = " + response.code());//200
        System.out.println("message = " + response.message());//OK
        System.out.println("headers = " + response.headers());

        String responseBody_xml = response.body().string();

        System.out.println(responseBody_xml);
        Map<String, String> responseBodyMap = WXPayUtil.xmlToMap(responseBody_xml);
        String return_code = responseBodyMap.get("return_code");
        String return_msg = responseBodyMap.get("return_msg");
        if(return_code.equalsIgnoreCase("SUCCESS")){
            String result_code = responseBodyMap.get("result_code");
            if(result_code.equalsIgnoreCase("SUCCESS")){
                /*
                SUCCESS--支付成功
                REFUND--转入退款
                NOTPAY--未支付
                CLOSED--已关闭
                REVOKED--已撤销(刷卡支付)
                USERPAYING--用户支付中
                PAYERROR--支付失败(其他原因，如银行返回失败)
                ACCEPT--已接收，等待扣款
                 */
                String trade_state = responseBodyMap.get("trade_state");
                String trade_state_desc =responseBodyMap.get("trade_state_desc");
                String total_fee =responseBodyMap.get("total_fee");

                if(trade_state.equalsIgnoreCase("SUCCESS")){//支付成功
                    paySuccess(orderId,Integer.valueOf(total_fee));
                    return  new AjaxResult(200,"OK",trade_state_desc);
                }

                return  new AjaxResult(200,"OK",trade_state_desc);
            }else{
                String err_code_des = responseBodyMap.get("err_code_des");
                return  new AjaxResult(200,"OK",err_code_des);
            }
        }

        return  new AjaxResult(200,"OK",return_msg);
    }

    private void paySuccess(Long orderId,Integer totalFee){
        //1、插入一条支付记录



    }
}
